package com.guoq.utils;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Administrator on 2017/7/17.
 */
public class SecurityUtils {

    public static final String KEY_SHA = "SHA";
    public static final String KEY_MD5 = "MD5";
    public static final String KEY_MAC = "HmacMD5";
    public static final String KEY_SHA_256 = "SHA-256";


    public static String commonEncode(String sSource,String algorithm){
        String sRet = null;
        try
        {
            MessageDigest algo = MessageDigest.getInstance(algorithm);
            algo.update(sSource.getBytes());
            byte[] digesta = algo.digest();
            sRet = byte2hex(digesta);
        }
        catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        return sRet;
    }

    public static String md5SHAEncode(String sSource){
        String sRet = null;
        try
        {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(sSource.getBytes());
            byte[] digesta = md5.digest();
            sRet = byte2hex(digesta);

            MessageDigest sha = MessageDigest.getInstance("SHA");
            sha.update(sRet.getBytes());
            byte[] digesta2 = sha.digest();
            sRet = byte2hex(digesta2);
        }
        catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }
        return sRet;
    }



    private static String byte2hex(byte[] arr_bt){

        StringBuffer sBuf = new StringBuffer(arr_bt.length * 2);
        for (int i = 0; i < arr_bt.length; i++){
            sBuf.append(""+
                    "0123456789ABCDEF".charAt(0xf & arr_bt[i] >> 4)
                    + "0123456789ABCDEF".charAt(arr_bt[i] & 0xf));
        }
        return sBuf.toString();
    }
}
